package com.ruoyi.common.utils;

import com.ruoyi.common.core.domain.BaseSelect;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zouhuu
 * @description 树构建工具嘞
 * @date 2022/10/17 09:23:06
 */
public class TreeUtils {


    /**
     * 构建两级树
     * @param baseSelectList
     * @return
     */
    public static List<BaseSelect> buildTwoLevelTree(List<BaseSelect> baseSelectList) {
        // 构建树结构
        List<BaseSelect> twoLevelTree = baseSelectList.stream().filter(m -> m.getPid() == 0).map(
                item -> {
                    item.setChildren(getChildrenList(item, baseSelectList));
                    return item;
                }
        ).collect(Collectors.toList());
        return twoLevelTree;
    }

    /**
     * 获取子节点列表
     * @param tree
     * @param list
     * @return
     */
    public static List<BaseSelect> getChildrenList(BaseSelect tree, List<BaseSelect> list){
        List<BaseSelect> children = list.stream().filter(item -> Objects.equals(item.getPid(), tree.getId())).map(
                (item) -> {
                    item.setChildren(getChildrenList(item, list));
                    return item;
                }
        ).collect(Collectors.toList());
        return children;
    }
}
